package org.yxing.palpalgps.activity;

import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.yxing.palpalgps.AbstractTabActivity;
import org.yxing.palpalgps.ActionBar.OnActionBarListener;
import org.yxing.palpalgps.BaseActivity;
import org.yxing.palpalgps.R;
import org.yxing.palpalgps.adapter.FriendListAdapter;
import org.yxing.palpalgps.http.AsyncRequest;
import org.yxing.palpalgps.http.AsyncRequest.FetchListener;
import org.yxing.palpalgps.models.ListUserItem;
import org.yxing.palpalgps.models.User;
import org.yxing.palpalgps.oauth.OAuth;
import org.yxing.palpalgps.utils.Helper;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;

public class FirendActivity extends BaseActivity implements OnActionBarListener, OnItemClickListener, OnItemLongClickListener{
    
    private static final String TAG = "FirendActivity";
    private static final String FRIEND_DELETE = "friend/delete";
    
    private FriendListAdapter mAdapter;
    private ListView mListView;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.firend);
        
        mListView = (ListView) findViewById(android.R.id.list);
        mListView.setOnItemClickListener(this);
        mListView.setOnItemLongClickListener(this);
        mAdapter = new FriendListAdapter(this);
        mListView.setAdapter(mAdapter);
        fetchData();
    }
    
    public void onResume() {
        super.onResume();
        AbstractTabActivity parent = (AbstractTabActivity) getParent();
        parent.getActionBar().setOnActionBarListener(this);
    }
    
    /**
     * fetch data
     */
    public void fetchData() {
        AsyncRequest ar = new AsyncRequest(this);
        ar.fetch("friend/list", new FetchListener() {
            
            public void onError(int code, String msg) {
                
            }
            
            public void onComplete(JSONObject response) {
                try {
                    mAdapter.clear();
                    JSONObject result = response.getJSONObject(Helper.RESULT);
                    JSONArray friends = result.getJSONArray("friends");
                    for (int i = 0; i < friends.length(); i ++) {
                        JSONObject json = friends.getJSONObject(i);
                        ListUserItem model = new ListUserItem();
                        model.setUid(json.getInt(User.KEY_UID));
                        model.setName(json.getString(User.KEY_NAME));
                        model.setGender(json.getString(User.KEY_GENDER));
                        model.setPortrait(json.getString(User.KEY_FACE));
                        mAdapter.add(model);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    
    public void deleteFriend(final int position) {
        int uid = mAdapter.getItem(position).getUid();
        AsyncRequest ar = new AsyncRequest(this);
        List<BasicNameValuePair> params = OAuth.createAuthParams();
        params.add(new BasicNameValuePair("fuid", Integer.toString(uid)));
        ar.fetch(FRIEND_DELETE, params, new FetchListener() {
            
            public void onError(int code, String msg) {
                
            }
            
            public void onComplete(JSONObject response) {
                mAdapter.remove(position);
                displayToast(getString(R.string.toast_delect_firend_success));
            }
        });
    }
    
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        }
        
        return super.onKeyUp(keyCode, event);
    }

    public void onActionBarItemClick(int position) {
        switch (position) {
        case 0:
            fetchData();
            break;
        }
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ListUserItem fuser = mAdapter.getItem(position);
        Intent intent = new Intent(this, ChatActivity.class);
        
        intent.putExtra("fuid", Long.toString(id));
        intent.putExtra("name", fuser.getName());
        intent.putExtra("portrait", fuser.getPortrait());
        startActivity(intent);
    }

    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
        String[] items = {getString(R.string.delete)};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setItems(items, new OnClickListener() {
            
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    deleteFriend(position);
                }
            }
        });
        builder.setNegativeButton(getString(R.string.cancel), null);
        builder.create();
        builder.show();
        
        return false;
    }
}
